import { _decorator, Collider2D, Component, Contact2DType, instantiate, IPhysics2DContact, Node, PhysicsSystem2D, Prefab, RigidBody2D, v2, Vec2, Vec3 } from 'cc';
import { GameWeapon } from './GameWeapon';
import { Gun } from './Gun';
import PlayerController from '../PlayerController';
import { ResourceUtil } from '../AshFramework/Utils/ResourceUtil';
import { GameManager } from './GameManager';
import { HintController } from './HintController';
import { BULLETNAME, CAPACITY, Constant, WEAPON, WEAPONBULLET } from '../AshFramework/Datas/Constant';
import { ZTool } from '../AshFramework/Utils/ZTool';
import { Magazine } from './Magazine';
import { EventManager, MyEvent } from '../AshFramework/Managers/EventManager';
import { Reload } from './Loading';
import { BundleManager, Bundles } from '../AshFramework/Managers/BundleManager';
import { EnemyController } from './EnemyController';
import { TLWLSJ_UIManager } from './UIManager';
import { AudioManager, Audios } from '../AshFramework/Managers/AudioManager';
const { ccclass } = _decorator;

enum Ani {
    None = "",
    Fire = "gongji",
}

@ccclass('GameWeapon_GMSQ')
export class GameWeapon_GMSQ extends GameWeapon {

    QK: Node = null;

    private _data: Gun = null;
    private _capacity: number = 0;

    private _pos: Vec3 = new Vec3();
    private _harm: number = 180;
    private _armor: number = 999;

    protected start(): void {
        this.QK = this.node.getChildByName("枪口");

        this._data = this.Data as Gun;
        PlayerController.Instance.WeaponTs = this;
        this._capacity = CAPACITY[ZTool.GetEnumKeyByValue(WEAPON, this.WeaponType)];
        if (!this._data.CurMagazine) {
            this._data.CurMagazine = new Magazine(this._capacity);
        }
        this.scheduleOnce(() => { this.updateWeaponShow(this._data.CurMagazine); }, 0.1)
    }

    //却换弹夹
    loadBullet() {
        if (TLWLSJ_UIManager.Instance.IsLock) {
            this.getWeapon();
            return;
        }
        if (this._data.CurMagazine.Bullets.length >= this._capacity) {
            ResourceUtil.LoadPrefab("UI/Hint").then((prefab: Prefab) => {
                const node: Node = instantiate(prefab);
                node.parent = GameManager.Instance.Canvas;
                node.getComponent(HintController).showHint("弹夹已满！");
            })
            return;
        }

        if (!GameManager.Instance.IsRecharge) {
            TLWLSJ_UIManager.Instance.showCDZPanel(() => {
                TLWLSJ_UIManager.Instance.closeCDZPanel();
                const weaponName = ZTool.GetEnumKeyByValue(WEAPON, this.WeaponType);
                this._data.CurMagazine = new Magazine(CAPACITY[weaponName], WEAPONBULLET[weaponName]);
                this.updateWeaponShow(this._data.CurMagazine);
            });
            return;
        }

        this.IsReload = true;
        const needNum = this._capacity - this._data.CurMagazine.Bullets.length;

        for (let i = 0; i < needNum; i++) {
            this._data.CurMagazine.Bullets.push(BULLETNAME.GSQ);
        }
        BundleManager.LoadPrefab(Bundles.Prefabs, "装弹中").then((prefab: Prefab) => {
            const reload: Node = instantiate(prefab);
            reload.parent = GameManager.Instance.Canvas;
            reload.getComponent(Reload).reload(() => {
                this.IsReload = false;
                this.updateWeaponShow(this._data.CurMagazine);
                this.IsStop ? this.endAttack() : this.attack();
            })
        })
    }

    attack() {
        if (TLWLSJ_UIManager.Instance.IsLock) {
            this.getWeapon();
            return;
        }
        if (!this.isAttack()) return;
        if (this.IsStop) {
            this.playAni(Ani.None, false);
            return;
        }
        if (this._data.CurMagazine && this._data.CurMagazine.Bullets.length > 0) {
            const bullet = this._data.CurMagazine.Bullets.shift();
            this.IsFire = true;
            AudioManager.PlaySound(Audios.GMSQ);
            this.playAni(Ani.Fire, false, () => {
                this.State = Ani.None;
                this.IsFire = false;
                this.castRayAll(this.QK.getWorldPosition().clone(), v2(PlayerController.Instance.DirX, PlayerController.Instance.DirY));
                this.updateWeaponShow(this._data.CurMagazine);
                this.attack();
                //发起攻击
            });
        } else {
            this.loadBullet();
            this.endAttack();
        }
    }

    castRayAll(origin: Vec3, direction: Vec2, distance: number = 10000) {

        const startPos = v2(origin.x, origin.y);
        const targetPos = startPos.clone().add(direction.multiplyScalar(distance));
        const results = PhysicsSystem2D.instance.raycast(startPos, targetPos, 3);

        // 检测所有碰撞
        if (results.length > 0) {
            for (const result of results) {
                // 获取碰撞点信息
                const hitCollider = result.collider;
                if (hitCollider.group == Constant.Group.ENEMY) {
                    // console.error('射线击中物体:' + hitCollider.node.name);
                    hitCollider.node.getComponent(EnemyController).hit(this._harm, this._armor);
                }
            }
        }

    }


    protected onEnable(): void {
        super.onEnable();
        EventManager.on(MyEvent.RELOAD, this.loadBullet, this);
    }

    protected onDisable(): void {
        super.onDisable();
        EventManager.off(MyEvent.RELOAD, this.loadBullet, this);
    }

}


